package com.scs.application.modules.dept.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.ReagentTeam;
import com.scs.application.modules.base.service.ReagentTeamService;
import com.scs.application.modules.dept.entity.Use;
import com.scs.application.modules.dept.entity.UseDtl;
import com.scs.application.modules.dept.entity.UseMergeDtl;
import com.scs.application.modules.dept.service.UseDtlService;
import com.scs.application.modules.dept.service.UseMergeDtlService;
import com.scs.application.modules.dept.service.UseService;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 科室消耗单主表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/dept/use")
public class UseController extends FlowController<UseService, Use> {
    @Autowired
    private UseMergeDtlService useMergeDtlService;
    @Autowired
    private UseDtlService useDtlService;
    @Autowired
    private ReagentTeamService reagentTeamService;

    @GetMapping("/preview")
    public void preview(@RequestParam(name = "id") String id,
                        HttpServletResponse response) throws IOException {
        service.preview(id, response);
    }

    /**
     * 获取数据列表
     */
    @GetMapping("/pageForMerge")
    public PageResult pageForMerge() {
        QueryContext queryContext = QueryContextHolder.currentContext();

        List<UseMergeDtl> useMergeDtlList = useMergeDtlService.list();
        List<String> useDtlIds = useMergeDtlList.stream().map(o -> o.getRefId()).collect(Collectors.toList());

        // 排除已合并的消耗单
        List<String> excludeIds = Lists.newArrayList();
        if (!useDtlIds.isEmpty()){
            List<UseDtl> useDtls = useDtlService.list(Wrappers.<UseDtl>query().in("id", useDtlIds));
            Map<String, List<UseDtl>> useDtlMap = useDtls.stream().collect(Collectors.groupingBy(UseDtl::getUseId));

            for (String s : useDtlMap.keySet()) {
                List<UseDtl> useDtlList = useDtlService.list(Wrappers.<UseDtl>query().eq("use_id", s));
                int allNum = useDtlList.size();
                int mergeNum = useDtlMap.get(s).size();
                if (allNum == mergeNum){
                    excludeIds.add(s);
                }
            }
        }
       QueryWrapper queryWrapper = queryContext.getWrapper();
        if (queryWrapper == null) {
            queryWrapper =Wrappers.<Use>query();
        }
        queryWrapper.eq("flow_status","end");
        queryWrapper.notIn(!excludeIds.isEmpty(),"id", excludeIds );

        IPage pageResult = service.page(queryContext.getPage(),queryWrapper);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }
    @GetMapping("/getDeptUse")
    public RestResult getDeptUse(@RequestParam("code") String code) {
        return RestResult.ok("ok",service.getDeptUse(code));
    }

    /**
     * @Description：顶部合计覆盖
     */
    @GetMapping("/sumTop")
    @Override
    public RestResult sumTop(String sumFields) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        queryContext.getWrapper().getExpression().getOrderBy().clear();
        return RestResult.ok("查询成功", service.getMap(queryContext.getWrapper().select(" sum( case flag_use_red_type when 1 then abs(amount)*-1 else amount end ) as amount")));
    }

    private void fillEntity(Use entity) {
        if (StringUtils.isNotBlank(entity.getReagentTeamId())) {
            ReagentTeam reagentTeam =reagentTeamService.getById(entity.getReagentTeamId());
            if (reagentTeam != null) {
                entity.setReagentTeamName(reagentTeam.getName());
            }
        }

        entity.setCountDtl(useDtlService.count(Wrappers.<UseDtl>query().select("id").eq("use_id",entity.getId())));
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Use entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Use entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }

}
